package com.coldwindblows.blog.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.bo.StatisticsBo;
import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.dto.LogActions;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.CommentDo;
import com.coldwindblows.blog.pojo.ContentDo;
import com.coldwindblows.blog.pojo.LogDo;
import com.coldwindblows.blog.pojo.UserDo;
import com.coldwindblows.blog.service.ILogService;
import com.coldwindblows.blog.service.ISiteService;
import com.coldwindblows.blog.service.IUserService;
import com.coldwindblows.blog.utils.TaleUtils;

/**
 * 后台管理首页
 * Created by ColdWindBlows on 2018/07/06
 */
@Controller("adminIndexController")
@RequestMapping("/admin")
@Transactional(rollbackFor = TipException.class)
@SuppressWarnings("rawtypes")
public class IndexController extends BaseController {

	@Autowired
	private ISiteService siteService;
	
	@Autowired
	private ILogService logService;
	
	@Autowired
	private IUserService userService;
	
	/**
	 * 页面跳转
	 * @param model
	 * @return
	 */
	@GetMapping({"", "/index"})
	public String index(Model model) {
		List<CommentDo> commentList = siteService.recentComments(5);
		List<ContentDo> contentList = siteService.recentContents(5);
		StatisticsBo statstics = siteService.getStatistics();
		// 取最新的20条日志
		List<LogDo> logs = logService.getLogs(1, 5);
		
		model.addAttribute("comments", commentList);
		model.addAttribute("articles", contentList);
		model.addAttribute("statistics", statstics);
		model.addAttribute("logs", logs);
		
		return "admin/index";
	}
	
	/**
	 * 个人设置页面
	 * @return
	 */
	@GetMapping("/profile")
	public String profile() {
		return "admin/profile";
	}
	
	/**
	 * 保存个人信息
	 * @param screenName
	 * @param email
	 * @param request
	 * @param session
	 * @return
	 */
	@PostMapping("/profile")
	@ResponseBody
	public RestResponseBo saveProfile(@RequestParam String screenName, @RequestParam String email, HttpServletRequest request, HttpSession session) {
		UserDo user = this.user(request);
		if(StringUtils.isNotBlank(screenName) && StringUtils.isNotBlank(email)) {
			UserDo temp = new UserDo();
			temp.setUid(user.getUid());
			temp.setScreenName(screenName);
			temp.setEmail(email);
			userService.updateByUid(temp);
			logService.insertLog(LogActions.UP_INFO.getAction(), JSON.toJSONString(temp), request.getRemoteAddr(), user.getUid());
			
			// 更新session中的数据
			UserDo origin = (UserDo) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
			origin.setScreenName(screenName);
			origin.setEmail(email);
			session.setAttribute(WebConst.LOGIN_SESSION_KEY, origin);
		}
		
		return RestResponseBo.ok();
	}
	
	/**
	 * 修改密码
	 * @param oldPassword
	 * @param password
	 * @param request
	 * @param session
	 * @return
	 */
	@PostMapping("/password")
	@ResponseBody
	public RestResponseBo upPwd(@RequestParam String oldPassword, @RequestParam String password, HttpServletRequest request, HttpSession session) {
		UserDo user = this.user(request);
		if(StringUtils.isBlank(oldPassword) || StringUtils.isBlank(password)) {
			return RestResponseBo.fail("请确认信息输入完整");
		}
		
		String oldSalt = user.getSalt();
		if(!user.getPassword().equals(TaleUtils.getHashPassword(oldSalt, oldPassword))) {
			return RestResponseBo.fail("旧密码错误");
		}
		
		if(password.length() < 6 || password.length() > 14) {
			return RestResponseBo.fail("请输入6-14位的密码");
		}
		
		try {
			UserDo temp = new UserDo();
			temp.setUid(user.getUid());
			String salt = TaleUtils.getSalt();
			String pwd = TaleUtils.getHashPassword(salt, password);
			temp.setSalt(salt);
			temp.setPassword(pwd);
			userService.updateByUid(temp);
			logService.insertLog(LogActions.UP_PWD.getAction(), null, request.getRemoteAddr(), user.getUid());
			
			// 更新session中的数据
			UserDo origin = (UserDo) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
			origin.setSalt(salt);
			origin.setPassword(pwd);
			session.setAttribute(WebConst.LOGIN_SESSION_KEY, origin);
			return RestResponseBo.ok();
		} catch(Exception e) {
			String msg = "密码修改失败";
			if(e instanceof TipException) {
				msg = e.getMessage();
			}
			return RestResponseBo.fail(msg);
		}
	}
	
}
